import Description, { GRID_CONF } from '@/components/Description';
import { pcsControllerGetLastPcsData, pcsControllerGetPcsInfos } from '@/services/ess/devicePcs';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { useModel } from '@umijs/max';
import { Col, Flex, Form, Row, Select, Space } from 'antd';
import type { DescriptionsItemType } from 'antd/es/descriptions';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useIntl } from 'umi';
const RealtimeMonitor: React.FC = () => {
  const intl = useIntl();
  let realTimeInterval: any = null;
  const { initialState } = useModel('@@initialState');
  const [defaultValue, setDefaultValue] = useState('');
  const selectedPCS = useRef<any>(null);
  const OnlineOptions = useRef<any>(null);
  const WorkOptions = useRef<any>(null);
  const BreakStatusOptions = useRef<any>(null);
  const BreakBreakdownOptions = useRef<any>(null);
  const [pcsOptions, setPcsOptions] = useState<any[]>([]);
  const [columns, setColumns] = useState<DescriptionsItemType[]>([
    // 1
    {
      label: intl.formatMessage({ id: 'data.onlineStatus' }),
      key: 'onlineState',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'data.workStatus' }),
      children: '',
      key: 'workState',
    },
    {
      label: intl.formatMessage({ id: 'data.deviceModel' }),
      children: '',
      key: 'product',
    },
    {
      label: intl.formatMessage({ id: 'data.gcbStatus' }),
      children: '',
      key: 'stateInfo',
    },
    {
      label: intl.formatMessage({ id: 'data.gcbFault' }),
      children: '',
      key: 'faultInfo',
    },
    {
      label: intl.formatMessage({ id: 'data.igbtTempa' }),
      children: '',
      key: 'igbta',
    },
    {
      label: intl.formatMessage({ id: 'data.igbtTempb' }),
      children: '',
      key: 'igbtb',
    },
    {
      label: intl.formatMessage({ id: 'data.igbtTempc' }),
      children: '',
      key: 'igbtc',
    },
    {
      label: intl.formatMessage({ id: 'data.gridFrequency' }),
      children: '',
      key: 'gridFreq',
      span: 1,
    },
    // 2
    {
      label: intl.formatMessage({ id: 'data.ua' }),
      children: '',
      key: 'ua',
    },
    {
      label: intl.formatMessage({ id: 'data.ub' }),
      children: '',
      key: 'ub',
    },
    {
      label: intl.formatMessage({ id: 'data.uc' }),
      children: '',
      key: 'uc',
    },
    {
      label: intl.formatMessage({ id: 'data.ia' }),
      children: '',
      key: 'ia',
    },
    {
      label: intl.formatMessage({ id: 'data.ib' }),
      children: '',
      key: 'ib',
    },
    {
      label: intl.formatMessage({ id: 'data.ic' }),
      children: '',
      key: 'ic',
    },
    // 3
    {
      label: intl.formatMessage({ id: 'data.activePowerKw' }),
      children: '',
      key: 'activePower',
    },
    {
      label: intl.formatMessage({ id: 'data.reactivePowerKvar' }),
      children: '',
      key: 'reactivePower',
    },
    {
      label: intl.formatMessage({ id: 'data.apparentPowerKva' }),
      children: '',
      key: 'apparentPower',
    },
    {
      label: intl.formatMessage({ id: 'data.powerFactor' }),
      children: '',
      key: 'powerFactor',
    },
  ]);
  /**
   * 改变pcs名称
   * @param value
   */
  const changePCS = (value: string) => {
    pcsControllerGetLastPcsData({ code: value }).then((res) => {
      const newArrayData: any[] = [];
      let FormatterData = res.data || {};
      // 映射在线状态
      const onlineState = FormatterData.onlineState
        ? (OnlineOptions?.current || []).find((item) => {
            return Number(item.value) === Number(FormatterData.onlineState);
          })?.label
        : '--';
      FormatterData.onlineState = onlineState || '';
      // 映射工作状态
      const workState = FormatterData.workState
        ? (WorkOptions?.current || []).find((item) => {
            return Number(item.value) === Number(FormatterData.workState);
          })
        : '--';
      FormatterData.workState = workState?.label || '';
      // 映射断路器状态
      const stateInfo = FormatterData.stateInfo
        ? (BreakStatusOptions?.current || []).find((item) => {
            return Number(item.value) === Number(FormatterData.stateInfo);
          })
        : '--';
      FormatterData.stateInfo = stateInfo?.label || '';
      // 映射断路器故障
      const faultInfo = FormatterData.faultInfo
        ? (BreakBreakdownOptions?.current || []).find((item) => {
            return Number(item.value) === Number(FormatterData.faultInfo);
          })
        : '--';
      FormatterData.faultInfo = faultInfo?.label || '';
      columns.forEach((item) => {
        newArrayData.push({
          ...item,
          children: FormatterData[item.key],
        });
      });
      setColumns(newArrayData);
    });
  };

  /**
   * 获取PCS设备
   */
  const getRealtimeData = () => {
    pcsControllerGetPcsInfos({ stationId: initialState?.stationId }).then((res) => {
      if (res.data && res.data.length > 0) {
        setPcsOptions(res.data);
        setDefaultValue(res.data[0].code);
        selectedPCS.current = res.data[0].code;
        changePCS(res.data[0].code);
      }
    });
  };

  const getDictOptions = () => {
    Promise.all([
      fetchDictInfo(DATABASE_TYPE_ENUM.ONLINE_STATUS),
      fetchDictInfo(DATABASE_TYPE_ENUM.WORK_STATUS),
      fetchDictInfo(DATABASE_TYPE_ENUM.BREAKER_STATUS),
      fetchDictInfo(DATABASE_TYPE_ENUM.BREAKER_BREAKDOWN),
    ]).then((res) => {
      OnlineOptions.current = res[0];
      WorkOptions.current = res[1];
      BreakStatusOptions.current = res[2];
      BreakBreakdownOptions.current = res[3];
      getRealtimeData();
    });
  };
  useEffect(() => {
    if (realTimeInterval) {
      clearInterval(realTimeInterval);
    }
    getDictOptions();
    realTimeInterval = setInterval(() => {
      changePCS(selectedPCS.current);
    }, 60000);
    return () => {
      clearInterval(realTimeInterval);
    };
  }, []);

  const groupColumns = useMemo(() => {
    return [columns.slice(0, 9), columns.slice(9, 15), columns.slice(15)];
  }, [columns]);

  return (
    <>
      <Flex vertical={true} justify={'center'} style={{ marginTop: 20 }}>
        <Form
          colon={false}
          layout={'horizontal'}
          labelCol={{
            flex: `0 0 160px`,
          }}
        >
          <Row gutter={0}>
            <Col {...GRID_CONF}>
              <Form.Item
                label={intl.formatMessage({ id: 'stationRealtimeMonitoring.name' })}
                style={{ marginBottom: 0 }}
              >
                <Select
                  value={defaultValue}
                  options={pcsOptions}
                  placeholder={intl.formatMessage({ id: 'siteManage.selectPlease' })}
                  fieldNames={{
                    label: 'name',
                    value: 'code',
                  }}
                  onSelect={(value) => {
                    selectedPCS.current = value;
                    setDefaultValue(value);
                    changePCS(value);
                  }}
                  style={{ flex: 1 }}
                ></Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <Space direction="vertical" size={50} style={{ margin: '48px 0' }}>
          {groupColumns.map((item, index) => {
            return <Description key={index} items={item}></Description>;
          })}
        </Space>
      </Flex>
    </>
  );
};

export default RealtimeMonitor;
